package shop.converter;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import shop.IService;
import shop.model.City;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@Component
@FacesConverter(forClass = City.class)
public class CityConverter implements Converter {
    @Autowired
    private IService<City> cityService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if ("".equals(value)) {
            return null;
        }

        Long cityId = Long.valueOf(value);
        City city = cityService.read(cityId);
        return city;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if ("".equals(value.toString())) {
            return null;
        }

        return ((City) value).getId().toString();
    }
}
